// 关闭票务系统
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#define NUMS 5
int ticket = 5000;
// 静态初始化 互斥量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// 静态初始化 条件变量
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

int closed = 0; // 标记票务系统是否已关闭
void *threadRoutine(void *arg)
{
    char *s = (char *)arg;
    while (1)
    {
        // 添加互斥锁
        pthread_mutex_lock(&mutex);
        // 如果票务系统已关闭，线程退出
        while (ticket <= 0 && closed)
        {
            pthread_mutex_unlock(&mutex);
            pthread_exit(NULL); // 退出线程
        }

        // 等待条件变量
        while (ticket <= 0)
        {
            pthread_cond_wait(&cond, &mutex);
            break;
        }

        if (ticket > 0)
        {
            usleep(1000);
            printf("%s买到了第%d张票\n", s, ticket);
            ticket--;
            // 解锁
            pthread_mutex_unlock(&mutex);
        }
        else
        {
            pthread_mutex_unlock(&mutex);
            printf("退出\n");
            break;
        }
    }
}

int main()
{

    // 初始化互斥量

    // pthread_mutex_init(&mutex, NULL);
    pthread_t tids[NUMS];
    char *arr[] = {"张三", "李四", "王五", "赵六", "马七"};
    for (int i = 1; i <= 5; i++)
    {
        pthread_create(&tids[i - 1], NULL, threadRoutine, (void *)arr[i - 1]);
    }

    // 唤醒等待的线程
    while (ticket > 0)
    {
        pthread_cond_signal(&cond);
    }
    // 票务系统关闭，唤醒所有线程以便退出
    pthread_mutex_lock(&mutex);
    closed = 1;
    pthread_cond_broadcast(&cond); // 唤醒所有线程
    pthread_mutex_unlock(&mutex);
    // 主线程等待子线程结束
    for (int i = 1; i <= 5; i++)
    {
        pthread_join(tids[i - 1], NULL);
    }
    // pthread_mutex_destroy(&mutex);

    pthread_cond_destroy(&cond);
    return 0;
}